package websocket

import (
	"context"
	"fmt"
	"github.com/edgexfoundry/edgex-go/internal/core/data/container"
	"github.com/edgexfoundry/go-mod-bootstrap/v2/bootstrap/startup"
	"github.com/edgexfoundry/go-mod-bootstrap/v2/di"
	"net/http"
	"strconv"
	"sync"
)

func BootstrapHandler(ctx context.Context, wg *sync.WaitGroup, startupTimer startup.Timer, dic *di.Container) bool {
	configuration := container.ConfigurationFrom(dic.Get)
	port := configuration.WebSocket.Port
	hub := NewHub()
	go hub.Run()

	//注册请求对应的处理函数
	http.HandleFunc("/ws", func(rw http.ResponseWriter, r *http.Request) {
		ServeWs(hub, rw, r)
	})

	//wsc := NewWebsocketClientManager("127.0.0.1", strconv.Itoa(port), "/ws", 60)
	//wsc.Start()
	//
	//dic.Update(di.ServiceConstructorMap{
	//	"websocketclient": func(get di.Get) interface{} {
	//		return &wsc
	//	},
	//})

	//如果启动成功，该行会一直阻塞，hub.run()会一直运行
	if err := http.ListenAndServe(":"+strconv.Itoa(port), nil); err != nil {
		fmt.Printf("start http service error: %s\n", err)
	}

	return true
}
